﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using MaterialSkin.Controls;
using MySql.Data.MySqlClient;

namespace home_material_tool
{
    public partial class AddEditForm : MaterialForm
    {
        //0:add, 1:edit
        private int addEditFromFlag = 0;

        //add form
        public AddEditForm()
        {
            InitializeComponent();

            Common.MSkinManager.AddFormToManage(this);

            addEditFromFlag = 0;
            SetControlProperty(0);

        }
        //edit form
        public AddEditForm(int videoCat, string id, string cnName, string enName, string doubanScore,
            string year, string hmStatusStr, string type, string district, string duration, string remark)
        {
            InitializeComponent();

            Common.MSkinManager.AddFormToManage(this);

            addEditFromFlag = 1;
            SetControlProperty(1);

            SetEditData(videoCat, id, cnName, enName, doubanScore,
             year, hmStatusStr, type, district, duration, remark);


        }

        private void SetControlProperty(int addEditFromFlag)
        {
            //add
            if (addEditFromFlag == 0)
            {
                this.mBtnAdd.Visible = true;
                this.mBtnUpdate.Visible = false;
                this.mLblID.Visible = false;
            }
            //ediit
            else if (addEditFromFlag == 1)
            {
                this.mBtnAdd.Visible = false;
                this.mBtnUpdate.Visible = true;
                this.mLblID.Visible = true;
            }
        }

        private void SetEditData(int videoCat, string id, string cnName, string enName, string doubanScore,
            string year, string hmStatusStr, string type, string district, string duration, string remark)
        {
            switch(videoCat)
            {
                case 0:
                    this.mRadioMovie.Checked = true;
                    break;
                case 1:
                    this.mRadioTVSeries.Checked = true;
                    break;
                default:
                    break;
            }
            switch (hmStatusStr)
            {
                case "未下载":
                    this.mRadioNotDownload.Checked = true;
                    break;
                case "已下载":
                    this.mRadioDownloaded.Checked = true;
                    break;
                case "已看":
                    this.mRadioSeen.Checked = true;
                    break;
                case "要删":
                    this.mRadioToDelete.Checked = true;
                    break;
                case "已删":
                    this.mRadioDeleted.Checked = true;
                    break;
                default:
                    this.mRadioNotDownload.Checked = true;
                    break;
            }

            this.mTxtCnName.Text = cnName;
            this.mTxtEnName.Text = enName;
            this.mTxtDoubanScore.Text = doubanScore;
            this.mTxtYear.Text = year;
            this.mTxtType.Text = type;
            this.mTxtCountry.Text = district;
            this.mTxtDuration.Text = duration;
            this.mTxtRemark.Text = remark;
            this.mLblID.Text = "id=" + id;
        }



        private async void mBtnAdd_Click(object sender, EventArgs e)
        {
            MaterialSnackBar snackBar = new MaterialSnackBar();
            try
            {
                string tableName = mRadioMovie.Checked ? CommonSql.MovieTableName : CommonSql.TVSeriesTableName;
                string cnName = mTxtCnName.Text.Trim().Replace("'", "''");
                string enName = mTxtEnName.Text.Trim().Replace("'", "''");
                string releasedyear = mTxtYear.Text.Trim();
                if(string.IsNullOrEmpty(cnName) && string.IsNullOrEmpty(enName) || string.IsNullOrEmpty(releasedyear))
                {
                    snackBar.BarType = MaterialSnackBar.SnackBarType.Warning;
                    snackBar.Text = "名称或上映年份为空";
                    snackBar.Show(this);
                    return;
                }
                //
                string doubanScore = mTxtDoubanScore.Text.Trim();
                string IMDBScore = mTxtIMDBScore.Text.Trim();
                string movieDuration = mTxtDuration.Text.Trim();

                int hmStatus = 0;
                if (mRadioNotDownload.Checked)
                    hmStatus = 0;
                else if (mRadioDownloaded.Checked)
                    hmStatus = 1;
                else if (mRadioSeen.Checked)
                    hmStatus = 2;
                else if (mRadioToDelete.Checked)
                    hmStatus = 3;
                else if (mRadioDeleted.Checked)
                    hmStatus = 4;
                //using regular expression to delete blank white
                string countryType = Regex.Replace(mTxtCountry.Text, @"\s", "");
                string movieType = Regex.Replace(mTxtType.Text, @"\s", "");
                string remark = mTxtRemark.Text.Trim();

                
                   string insertSql = "insert ignore into " + tableName + "(cn_name, en_name, released_year,douban_score,imdb_score,hm_status,country_type,movie_type,movie_duration,remark,create_time,update_time)" +
                    $"values('{cnName}', '{enName}', '{releasedyear}', '{doubanScore}', '{IMDBScore}', '{hmStatus}', '{countryType}','{movieType}','{movieDuration}','{remark}', SYSDATE(),SYSDATE())";

                string errStr = string.Empty;
                if (CommonSql.MysqlConn.State == ConnectionState.Closed)
                    errStr = await CommonSql.AsyncOpenDB();

                //db connection opened successfully
                if(errStr == string.Empty)
                {
                    MySqlCommand comm = new MySqlCommand(insertSql, CommonSql.MysqlConn);

                    int recCnt = comm.ExecuteNonQuery();
                    if (recCnt > 0)
                    {
                        snackBar.BarType = MaterialSnackBar.SnackBarType.Suceesss;
                        snackBar.Text = "插入数据成功";
                    }
                    else
                    {
                        snackBar.BarType = MaterialSnackBar.SnackBarType.Warning;
                        snackBar.Text = "该条数据已存在";
                        string alterSql = $"alter table {tableName}  AUTO_INCREMENT=1;";
                        comm.CommandText = alterSql;
                        comm.ExecuteNonQuery();
                    }
                }
                else //or failed
                {
                    snackBar.BarType = MaterialSnackBar.SnackBarType.Danger;
                    snackBar.Text = errStr;
                }
            }
            catch(Exception ex)
            {
                snackBar.BarType = MaterialSnackBar.SnackBarType.Danger;
                snackBar.Text = ex.Message;
            }

            snackBar.Show(this);

        }

        private void mBtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private async void mBtnUpdate_Click(object sender, EventArgs e)
        {
            MaterialSnackBar snackBar = new MaterialSnackBar();
            try
            {
                string id = this.mLblID.Text.Substring(3);
                string tableName = mRadioMovie.Checked ? CommonSql.MovieTableName : CommonSql.TVSeriesTableName;
                //the char "'" is not stored in database, so use the "''".
                string cnName = mTxtCnName.Text.Trim().Replace("'", "''");
                string enName = mTxtEnName.Text.Trim().Replace("'", "''");
                string releasedyear = mTxtYear.Text.Trim();
                if (string.IsNullOrEmpty(cnName) && string.IsNullOrEmpty(enName) || string.IsNullOrEmpty(releasedyear))
                {
                    snackBar.BarType = MaterialSnackBar.SnackBarType.Warning;
                    snackBar.Text = "名称或上映年份为空";
                    snackBar.Show(this);
                    return;
                }
                string doubanScore = mTxtDoubanScore.Text.Trim();
                string IMDBScore = mTxtIMDBScore.Text.Trim();
                string movieDuration = mTxtDuration.Text.Trim();

                int hmStatus = 0;
                if (mRadioNotDownload.Checked)
                    hmStatus = 0;
                else if (mRadioDownloaded.Checked)
                    hmStatus = 1;
                else if (mRadioSeen.Checked)
                    hmStatus = 2;
                else if (mRadioToDelete.Checked)
                    hmStatus = 3;
                else if (mRadioDeleted.Checked)
                    hmStatus = 4;

                //using regular expression to delete blank white
                string countryType = Regex.Replace(mTxtCountry.Text, @"\s", "");
                string movieType = Regex.Replace(mTxtType.Text, @"\s", "");
                string remark = mTxtRemark.Text.Trim();
                //
                string updateSql = "update " + tableName + $" set cn_name='{cnName}',en_name='{enName}',released_year='{releasedyear}'," +
                    $"douban_score='{doubanScore}',imdb_score='{IMDBScore}',hm_status='{hmStatus}',country_type='{countryType}',movie_type='{movieType}',movie_duration='{movieDuration}',remark='{remark}',update_time=SYSDATE() where id=" + id;


                string errStr = string.Empty;
                if (CommonSql.MysqlConn.State == ConnectionState.Closed)
                    errStr = await CommonSql.AsyncOpenDB();

                //db connection opened successfully
                if (errStr == string.Empty)
                {
                    MySqlCommand comm = new MySqlCommand(updateSql, CommonSql.MysqlConn);

                    int recCnt = comm.ExecuteNonQuery();
                    if (recCnt > 0)
                    {
                        snackBar.BarType = MaterialSnackBar.SnackBarType.Suceesss;
                        snackBar.Text = "更新数据成功";
                    }
                    else
                    {
                        snackBar.BarType = MaterialSnackBar.SnackBarType.Warning;
                        snackBar.Text = "记录数据没变";
                    }
                }
                else //or failed
                {
                    snackBar.BarType = MaterialSnackBar.SnackBarType.Danger;
                    snackBar.Text = errStr;
                }


            }
            catch(Exception ex)
            {
                snackBar.BarType = MaterialSnackBar.SnackBarType.Danger;
                snackBar.Text = ex.Message;
            }
            snackBar.Show(this);
        }

        const int WM_KEYDOWN = 256;
        const int WM_SYSKEYDOWN = 260;
        //overriding WndProc(ref Message m) to accept the key message seems failed
        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
        {

            if (msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN)
            {
                switch (keyData)
                {
                    case Keys.Enter:
                        if (this.mBtnAdd.Visible)
                            this.mBtnAdd_Click(null, null);
                        else if (this.mBtnUpdate.Visible)
                            this.mBtnUpdate_Click(null, null);
                        return true;
                        break;
                }

            }
            //other key command continues
            return false;
        }
        //private void mRadioDeleted_CheckedChanged(object sender, EventArgs e)
        //{
        //    if(addEditFromFlag == 0 && mRadioDeleted.Checked)
        //    {
        //        if(this.mTxtRemark.Text.Length >= mRadioDeleted.Text.Length)
        //        this.mTxtRemark.Text = this.mTxtRemark.Text.Replace(this.mTxtRemark.Text, mRadioDeleted.Text + this.mTxtRemark.Text.Substring(3));
        //    }
        //}

        //private void mRadioToDelete_CheckedChanged(object sender, EventArgs e)
        //{

        //}

        //private void mRadioSeen_CheckedChanged(object sender, EventArgs e)
        //{

        //}

        //private void mRadioDownloaded_CheckedChanged(object sender, EventArgs e)
        //{

        //}

        //private void mRadioNotDownload_CheckedChanged(object sender, EventArgs e)
        //{

        //}
    }
}
